package com.itheima.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;

public class JsonUtil {
    private JsonUtil(){}
    private static ObjectMapper mapper = new ObjectMapper();
    /*
    * 将对象转成json字符串
    * */
    public static String obj2JsonStr(Object obj){

        try {
            return mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
    /*
    * 将json字符串转成Bean对象
    * */
    public static<T> T jsonStr2Bean(String jsonStr,Class<T> cls){
        try {
            return mapper.readValue(jsonStr,cls);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /*
    * 将json字符串转成List或者Map集合
    * */
    public static<T> T jsonStr2ListOrMap(String jsonStr, TypeReference<T> tr){
        try {
            return mapper.readValue(jsonStr,tr);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    //将请求中的json字符串转换成Bean对象
   public static<T> T req2Bean(HttpServletRequest req,Class<T> cls){
       try {
           BufferedReader reader = req.getReader();
           String jsonStr = reader.readLine();
           return jsonStr2Bean(jsonStr,cls);
       } catch (IOException e) {
           e.printStackTrace();
       }
       return null;
   }

    //将请求中的json字符串转换成List或Map集合
    public static<T> T req2ListOrMap(HttpServletRequest req,TypeReference<T> tr){
        try {
            BufferedReader reader = req.getReader();
            String jsonStr = reader.readLine();
            return jsonStr2ListOrMap(jsonStr,tr);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
